﻿using MyOCR_WPF.Tool;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Security.Cryptography;
using System.Text;

namespace MyOCR_WPF.OCRHelper
{
    //ocr.tencentcloudapi.com 
    class TengXunOCR : IOCR
    {
        // 腾讯云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String SecretId;
        // 腾讯云中开通对应服务应用的 Secret Key
        private static String SecretKey;
        static TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        Int64 currentTime = Convert.ToInt64(ts.TotalSeconds);

        public TengXunOCR()
        {
            SecretId = ConfigurationManager.AppSettings["Tengxun_Id"];
            SecretKey = ConfigurationManager.AppSettings["Tengxun_Key"];
        }

        //计算签名
        protected string getSign(string base64img)
        {
            string sign = string.Format("POSTocr.tencentcloudapi.com/?Action=GeneralBasicOCR&ImageBase64=" + base64img + "&Nonce=1223455&Region=ap-guangzhou&SecretId=" + SecretId + "&Timestamp=" + currentTime + "&Version=2018-11-19");


            //return hash_hmac(sign, Program._config.TengXun_Secret_Key);
            var enc = Encoding.UTF8;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(SecretKey));
            hmac.Initialize();

            byte[] buffer = enc.GetBytes(sign);
            return Convert.ToBase64String(hmac.ComputeHash(buffer));
        }

        public string SendImg(Bitmap img)
        {
            String authHost = "https://ocr.tencentcloudapi.com/";
            RestClient restclient = new RestClient(authHost);
            RestRequest request = new RestRequest(Method.POST);
            request.AddHeader("host", "ocr.tencentcloudapi.com");
            request.AddParameter("Action", "GeneralBasicOCR");
            request.AddParameter("Version", "2018-11-19");
            request.AddParameter("Region", "ap-guangzhou");
            request.AddParameter("Timestamp", currentTime);//
            request.AddParameter("Nonce", "1223455");//
            request.AddParameter("SecretId", SecretId);
            request.AddParameter("Signature", getSign(ImageProcessing.ImageToBase64(img)));
            request.AddParameter("ImageBase64", ImageProcessing.ImageToBase64(img));
            var result = restclient.Execute(request);
            dynamic json = JsonConvert.DeserializeObject(result.Content);
            var lst = new List<string>();
            foreach (var item in json.Response.TextDetections)
            {
                lst.Add(item.DetectedText.ToString());
            }
            return string.Join("", lst);
        }
    }
}
